package com.zmn.oms.api.controller.third.baidu_mall;

import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.utils.RequestUtil;
import com.zmn.oms.third.baidu_dtw.BaiduDtwConsts;
import com.zmn.oms.third.baidu_mall.BaiduMallConsts;
import com.zmn.oms.third.baidu_mall.service.BaiduMallService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

/**
 * 类描述：
 *
 * @author LiangHailong
 * @date 2021/06/17 15:08
 */
@RestController
@RequestMapping("/baidu/mall")
@Slf4j
public class BaiduMallController {
    @Autowired
    private BaiduMallService baiduMallService;

    @RequestMapping("/order")
    @ResponseBody
    public ResultDTO order(HttpServletRequest request) {
        String appId = request.getParameter("appId");
        String data = request.getParameter("data");
        String sign = request.getParameter("sign");
        log.info("【{}】收到新单消息！ appId:[{}], data:[{}], sign=[{}]", BaiduMallConsts.NAME, appId, data, sign);

        try {
            validateParams(appId, data, sign);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultDTO.fail(e.getMessage());
        }

        try {
            baiduMallService.procMsg(data, Integer.parseInt(appId));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultDTO.fail("失败");
        }

        return ResultDTO.success();
    }

    private void validateParams(String appId, String content, String sign) {
        if (StringUtils.isBlank(content) || StringUtils.isBlank(sign) || StringUtils.isBlank(appId)) {
            throw new RuntimeException("参数不全");
        }
        if (!Pattern.matches("^\\d+$", appId)) {
            throw new RuntimeException("渠道信息非法");
        }
        String toSign = DigestUtils.md5Hex(appId + content + "dce56474f1b847fb879d4180822af12d");
        if (!toSign.toUpperCase().equals(sign.toUpperCase())) {
            throw new RuntimeException("校验失败");
        }
    }
}
